package com.dragon.modules.yuegou.service.impl.member;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.common.exception.DragonException;
import com.dragon.modules.yuegou.entity.member.ShoppingCartEntity;
import com.dragon.modules.yuegou.entity.product.SkuEntity;
import com.dragon.modules.yuegou.entity.product.StockEntity;
import com.dragon.modules.yuegou.enums.code.BusinessCode;
import com.dragon.modules.yuegou.enums.code.MemberCode;
import com.dragon.modules.yuegou.enums.code.ProductCode;
import com.dragon.modules.yuegou.enums.member.ShoppingCartShoppingType;
import com.dragon.modules.yuegou.mapper.member.ShoppingCartMapper;
import com.dragon.modules.yuegou.model.member.ShoppingCart;
import com.dragon.modules.yuegou.model.product.Attribute;
import com.dragon.modules.yuegou.query.member.ShoppingCartQuery;
import com.dragon.modules.yuegou.service.member.ShoppingCartService;
import com.dragon.modules.yuegou.service.product.AttributeService;
import com.dragon.modules.yuegou.service.product.SkuService;
import com.dragon.modules.yuegou.service.product.SpuService;
import com.dragon.modules.yuegou.service.product.StockService;
import com.dragon.modules.yuegou.web.Check;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 购物车 服务实现
 *
 * @author pbuilder generated
 * @date 2019-04-17 15:08:01
 * @version 2.0
 */
@Service("memShoppingCartService")
public class ShoppingCartServiceImpl
		extends ServiceImpl<ShoppingCartMapper, ShoppingCartEntity>
		implements ShoppingCartService {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private StockService stockService;

    @Autowired
    private AttributeService attributeService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private SpuService spuService;

    private static final String SHOPPING_CART_ID_IS_EMPTY = "购物车id不能为空";

    private static final String MEMBER_ID_IS_EMPTY = "会员id为空";
	@Override
	public void addCart(String memberId, String skuId, String busdId, int quantity) {
		this.addCart(memberId, skuId, busdId, quantity, ShoppingCartShoppingType.GOODS);
	}
    
	@Override
	public void addCart(String memberId, String skuId, String busdId, int quantity,
			ShoppingCartShoppingType shoppingType) {
		logger.debug("添加购物车开始 会员id={}，skuid={}，busdId={}，数量={}", memberId, skuId, busdId, quantity);
		Check.notNull(memberId, MemberCode.MEMBER_ID_IS_EMPTY.getMessage());
		Check.notNull(skuId, ProductCode.SKUID_NOTNULL.getMessage());
		Check.notNull(busdId, BusinessCode.BUSDID_NOTNULL.getMessage());
		quantity = quantity > 0 ? quantity : 1;
		SkuEntity sku = skuService.getCashById(skuId);
		if (sku == null || StringUtils.isEmpty(skuId)) {
			logger.debug("skuId  找不到sku skuid={}", skuId);
			throw new DragonException(ProductCode.SKU_NOT_EXSIT);
		}

		ShoppingCart shoppingCart = this.getBymemberIdAndSkuId(memberId, skuId, busdId);
		if (shoppingCart == null || shoppingCart.getId() == null) {
			logger.debug("添加购物车 购物车没有该商品 会员id={}，skuid={}，数量={}", memberId, skuId, quantity);
			shoppingCart = new ShoppingCart();
			shoppingCart.setSkuId(skuId);
			shoppingCart.setMemberId(memberId);
			shoppingCart.setMerchantId(sku.getMerchantId());
			shoppingCart.setSkuQuantity(quantity);
			shoppingCart.setStatus(false);
			shoppingCart.setBusdId(busdId);
			shoppingCart.setShoppingType(shoppingType);
			shoppingCart.setSkuAttr(sku.getAttrs());
            shoppingCart.setUseMemberPrice(true);
			this.save(shoppingCart);
		} else {
			logger.debug("添加购物车 购物车有该商品 会员id={}，skuid={}，数量={}", memberId, skuId, quantity);
			shoppingCart.setSkuQuantity(shoppingCart.getSkuQuantity() + quantity);
			shoppingCart.setSkuAttr(sku.getAttrs());
			shoppingCart.setMerchantId(sku.getMerchantId());
			this.baseMapper.updateById(shoppingCart);
		}
	}
    
    @Override
    public void editCart(String memberId, String cartId, int quantity) {
        logger.debug("修改购物车开始 会员id={}，cartId={}，数量={}",memberId,cartId,quantity);

        Check.notNull(memberId,MemberCode.MEMBER_ID_IS_EMPTY.getMessage());
        Check.notNull(cartId,SHOPPING_CART_ID_IS_EMPTY);
        quantity = quantity > 0 ? quantity:1;
        ShoppingCartEntity shoppingCart =this.getById(cartId);
        if (shoppingCart!=null && shoppingCart.getId() !=null){
            shoppingCart.setSkuQuantity(quantity);
            this.baseMapper.updateById(shoppingCart);
        }else {
            logger.error("修改购物车开始 没有该商品 会员id={}，cartId={}，数量={}",memberId,cartId,quantity);
        }
    }
    @Override
    public void editCartMemberPrice(String memberId, String cartId,Boolean usedMemberPrice) {
        logger.debug("修改购物车开始 会员id={}，cartId={}，是否使用会员价={}",memberId,cartId,usedMemberPrice);

        Check.notNull(memberId,MemberCode.MEMBER_ID_IS_EMPTY.getMessage());
        Check.notNull(cartId,SHOPPING_CART_ID_IS_EMPTY);
        if (usedMemberPrice ==null){
            usedMemberPrice = true;
        }
        ShoppingCartEntity shoppingCart =this.getById(cartId);
        if (shoppingCart!=null && shoppingCart.getId() !=null){
            shoppingCart.setUseMemberPrice(usedMemberPrice);
            this.baseMapper.updateById(shoppingCart);
        }else {
            logger.error("修改购物车开始 没有该商品 会员id={}，cartId={}，是否使用会员价={}",memberId,cartId,usedMemberPrice);
        }
    }
    @Override
    public void delCart(String memberId, String cartId) {
        logger.debug("删除购物车开始 会员id={}，cartId={}",memberId,cartId);

        Check.notNull(memberId,MemberCode.MEMBER_ID_IS_EMPTY.getMessage());
        Check.notNull(cartId,SHOPPING_CART_ID_IS_EMPTY);
        ShoppingCartEntity shoppingCart =this.getById(cartId);
        if (shoppingCart!=null && StringUtils.isNotEmpty(shoppingCart.getId())){
            this.removeById(shoppingCart.getId());
        }else {
            logger.error("删除购物车开始 没有该商品 会员id={}，cartId={}",memberId,cartId);
        }
    }

    @Override
    @Transient
    public void deleteCarts(String memberId, String[] cartIds) {
        logger.debug("批量删除购物车开始 会员id={}，cartIds={}",memberId,cartIds);
        Check.notNull(memberId,MemberCode.MEMBER_ID_IS_EMPTY.getMessage());
        Check.notEmpty(cartIds,SHOPPING_CART_ID_IS_EMPTY);
        for (String cartId : cartIds){
            this.delCart(memberId, cartId);
        }
    }

    @Override
    public void emptyCart(String memberId,String busdId) {
        logger.debug("删除购物车开始 会员id={}，busdId={}",memberId,busdId);
        Check.notEmpty(memberId, MemberCode.MEMBER_ID_IS_EMPTY.getMessage());
        Check.notNull(busdId,BusinessCode.BUSDID_NOTNULL.getMessage());

        ShoppingCartQuery query = new ShoppingCartQuery();
        query.setMemberId(memberId);
        query.setBusdId(busdId);
        this.remove(query.toQueryWrapper());
        logger.debug("删除购物车开始 会员id={}",memberId);
    }

    @Override
	public ShoppingCart getBymemberIdAndSkuId(String memberId, String skuId,String busdId) {
		Check.notNull(memberId,MEMBER_ID_IS_EMPTY);
		Check.notNull(skuId,"skuId为空");
        Check.notNull(busdId,BusinessCode.BUSDID_NOTNULL.getMessage());

		ShoppingCartQuery query = new ShoppingCartQuery();
		query.setDel(false);
		query.setStatus(false);
		query.setMemberId(memberId);
		query.setSkuId(skuId);
        query.setBusdId(busdId);
        List<ShoppingCartEntity> list= this.list(query.toQueryWrapper());
        if (CollectionUtils.isNotEmpty(list)){
            ShoppingCartEntity shoppingCart = list.get(0);
            if (list.size() >1){
                for (int i=1;i<list.size(); i++){
                    ShoppingCartEntity cart = list.get(i);
                    shoppingCart.setSkuQuantity(shoppingCart.getSkuQuantity()+cart.getSkuQuantity());

                    this.delCart(memberId,cart.getId());
                }
                this.baseMapper.updateById(shoppingCart);
            }
            return new ShoppingCart(shoppingCart);
        }
		return null;
	}

    @Override
    public List<ShoppingCart> pageByMemberId(String memberId,String busdId) {
        Check.notNull(memberId,MEMBER_ID_IS_EMPTY);
        Check.notNull(busdId,BusinessCode.BUSDID_NOTNULL.getMessage());
        Map<String,String> map = new HashMap<>();
        map.put(ShoppingCartEntity.COL_MEMBER_ID,memberId);
        map.put(ShoppingCartEntity.COL_BUSD_ID,busdId);
        map.put(ShoppingCartEntity.COL_SHOPPING_TYPE,ShoppingCartShoppingType.GOODS.getCode().toString());
        List<ShoppingCart> cartList = shoppingCartMapper.findByMemberId(map);
        cartList.stream().forEach(this::setStockAndAttr);
        return  cartList;
    }

    private void setStockAndAttr(ShoppingCart shoppingCart){
        if (shoppingCart!=null && shoppingCart.getSkuId()!=null){
            StockEntity stock = stockService.getById(shoppingCart.getSkuId());
            if (stock!=null){
                shoppingCart.setStock(stock.getStock());
            }

            List<Attribute> attributes = attributeService.findBySkuId(shoppingCart.getSkuId());
            shoppingCart.setAttributeList(attributes);
            shoppingCart.setMemberPrice(spuService.memberPrice(shoppingCart.getBusdId(),shoppingCart.getMemberId(),shoppingCart.getSpuId(),shoppingCart.getDiscountPrice()));
            shoppingCart.setSellBeginTime(spuService.getById(shoppingCart.getSpuId()).getSellBeginTime());
        }
    }


    @Override
	public List<ShoppingCart> findByMemberId(String memberId,String busdId) {
		Check.notNull(memberId,MEMBER_ID_IS_EMPTY);
		ShoppingCartQuery query = new ShoppingCartQuery();
		query.setDel(false);
		query.setStatus(false);
		query.setMemberId(memberId);
        query.setBusdId(busdId);
		return this.list(query.toQueryWrapper()).stream().map(ShoppingCart::new).collect(Collectors.toList());
	}

    @Override
    public List<ShoppingCart> findList(String[] cartIds) {
        Check.notNull(cartIds,"购物车id数组不能为空");
        List<ShoppingCart> cartList = new ArrayList<>();
        for (String cartId : cartIds){
            ShoppingCartEntity cart = this.getById(cartId);
            cartList.add(new ShoppingCart(cart));
        }

        return cartList;
    }
}